package com.zkflzl.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkflzl.store.common.BaseResponse;
import com.zkflzl.store.common.ErrorCode;
import com.zkflzl.store.common.ResultUtils;
import com.zkflzl.store.exception.BusinessException;
import com.zkflzl.store.exception.ThrowUtils;
import com.zkflzl.store.mapper.StoreMapper;
import com.zkflzl.store.model.dto.store.StoreAddRequest;
import com.zkflzl.store.model.dto.store.StoreListRequest;
import com.zkflzl.store.model.dto.store.StoreUpdateRequest;
import com.zkflzl.store.model.entity.Store;
import com.zkflzl.store.model.entity.User;
import com.zkflzl.store.service.StoreService;
import com.zkflzl.store.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

import static com.zkflzl.store.constant.UserConstant.ADMIN_ROLE;

/**
 * @author 21582
 * @description 针对表【tb_store(商品)】的数据库操作Service实现
 * @createDate 2024-03-19 11:10:46
 */
@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store>
        implements StoreService {
    @Resource
    private UserService userService;

    @Override
    public BaseResponse addStore(StoreAddRequest storeAddRequest, HttpServletRequest request) {
        // 判断是否登录
        User loginUser = userService.getLoginUser(request);
        if (storeAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long storeId = storeAddRequest.getStoreId();
        String name = storeAddRequest.getName();
        String spe = storeAddRequest.getSpe();
        String price = storeAddRequest.getPrice();
        Long shopId = storeAddRequest.getShopId();

        // 管理员添加，门店id不能为null
        if (userService.isAdmin(request)) {
            if (Objects.isNull(storeId)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "门店id不能为空");
            }
        }else{
            shopId = loginUser.getShopId();
        }



        if (StringUtils.isAnyBlank(name, spe, price, storeId.toString(),shopId.toString())) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }

        Store store = new Store();
        BeanUtils.copyProperties(storeAddRequest, store);
        store.setId(storeId);
        store.setUserId(loginUser.getId());
        store.setShopId(shopId);
        store.setId(storeId);
        boolean save = this.save(store);
        if (save) {
            return ResultUtils.success("添加成功");
        }
        return ResultUtils.error(ErrorCode.OPERATION_ERROR, "添加失败");
    }

    @Override
    public BaseResponse delStore(String storeId, HttpServletRequest request) {
        if (StringUtils.isBlank(storeId)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "商品id不能为空");
        }
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", storeId);
        Store store = this.getOne(queryWrapper);
        if (store == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "商品不存在");
        }

        // 是否登录
        User loginUser = userService.getLoginUser(request);

        // 非管理员
        if (!Objects.equals(loginUser.getUserRole(), ADMIN_ROLE)) {
            // 对应店员删除对应门店的商品
            String shopId = String.valueOf(store.getShopId());
            String userShopId = String.valueOf(loginUser.getShopId());
            if (!userShopId.equals(shopId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权删除其它门店商品");
            }
        }
        boolean remove = this.removeById(storeId);
        if (remove) {
            return ResultUtils.success("删除成功");
        }
        return ResultUtils.error(ErrorCode.OPERATION_ERROR, "删除失败");
    }

    @Override
    public BaseResponse selStore(StoreListRequest storeListRequest, HttpServletRequest request) {

        User user = userService.getLoginUser(request);

        String storeName = storeListRequest.getStoreName();
        String shopId = storeListRequest.getShopId();
        long current = storeListRequest.getCurrent();
        long pageSize = storeListRequest.getPageSize();

        if (StringUtils.isAnyBlank(current + "", pageSize + "")) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }

        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        // 管理员查  (查所有、查指定)
        if (Objects.equals(user.getUserRole(), ADMIN_ROLE)) {
            // 查所有
            if (!StringUtils.isBlank(shopId)) {
                queryWrapper
                        .eq("shopId", shopId);
            }
        } else {  // 普通门店的人
            // 查自己门店的
            queryWrapper
                    .eq("shopId", user.getShopId());
        }
        // 按时间升序排序
        queryWrapper
                .orderByAsc("createTime");

        if (!StringUtils.isBlank(storeName)) {
            queryWrapper
                    .eq("storeName", storeName);
        }

        // 分页查询
        Page<Store> page = this.page(new Page<>(current, pageSize), queryWrapper);

        return ResultUtils.success(page);
    }

    @Override
    public BaseResponse updateStore(StoreUpdateRequest storeUpdateRequest, HttpServletRequest request) {
        User user = userService.getLoginUser(request);

        Long storeId = storeUpdateRequest.getStoreId();
        String name = storeUpdateRequest.getName();
        String spe = storeUpdateRequest.getSpe();
        String price = storeUpdateRequest.getPrice();

        Store store = this.getById(storeId);
        // 非管理员操作
        if (!userService.isAdmin(request)) {
            Long userShopId = user.getShopId();
            Long shopId = store.getShopId();
            if (!Objects.equals(shopId, userShopId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "没有权限");
            }
        }

        if (StringUtils.isBlank(storeId + "")) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "门店id不能为空");
        }
        BeanUtils
                .copyProperties(storeUpdateRequest, store);

        boolean updatedById = this.updateById(store);
        ThrowUtils.throwIf(!updatedById, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(store);
    }
}




